package misakago

import (
	"errors"
	"github.com/streadway/amqp"
)

//rabbitmq 句柄
type Amqp struct {
	Conn  *amqp.Connection
	Chans map[string]*amqp.Channel
}

//设置连接
func (handle *Amqp) SetConnect(url string) error {
	if handle.Conn != nil {
		handle.Conn.Close()
	}

	conn, err := amqp.Dial(url)
	if err != nil {
		return errors.New("Queue connect fail")
	}
	handle.Conn = conn
	return nil
}

func (handle *Amqp) SetChannel(name string) error {
	_, ok := handle.Chans[name]
	//关闭旧的同名连接
	if ok {
		handle.Chans[name].Close()
	}
	channel, err := handle.Conn.Channel()

	if err != nil {
		return errors.New("Queue chanel fail")
	}
	handle.Chans[name] = channel
	return nil
}

func (handle *Amqp) Close() {
	handle.Conn.Close()
	for _, v := range handle.Chans {
		v.Close()
	}
}

/*
var conn *amqp.Connection
var send_channel *amqp.Channel
var receive_channel *amqp.Channel
var count = 0

var (
	logger = log.New(os.Stdout, "[misakago]:", log.LstdFlags)
)

const (
	queueName = "test"
	exchange  = ""
	mqurl     = "amqp://guest:guest@127.0.0.1:5672/"
)

func main() {
	go func() {
		for {
			push()
			time.Sleep(1 * time.Second)
		}
	}()

	time.Sleep(2 * time.Second)
	receive()
	fmt.Println("end")
	close()
}


func mqConnect() *amqp.Channel {
	var err error
	conn, err = amqp.Dial(mqurl)
	failOnErr(err, "failed to connect tp rabbitmq")

	channel, err := conn.Channel()
	failOnErr(err, "failed to open a channel")
	return channel
}

func close() {
	send_channel.Close()
	receive_channel.Close()
	conn.Close()
}

//连接rabbitmq server
func push() {

	if send_channel == nil {
		logger.Println("Try to connect:")
		send_channel = mqConnect()
		logger.Println("Try to connect success:")
	}
	msgContent := "hello world!"

	logger.Println("Try to push msg:", msgContent)

	send_channel.Publish(exchange, queueName, false, false, amqp.Publishing{
		ContentType: "text/plain",
		Body:        []byte(msgContent),
	})
}

func receive() {
	if receive_channel == nil {
		logger.Println("Receiver Try to connect:")
		receive_channel = mqConnect()
		logger.Println("Receiver Try to connect success:")
	}

	for {
		msgs, err := receive_channel.Consume(queueName, "", true, false, false, false, nil)
		failOnErr(err, "")

		go func() {
			//fmt.Println(*msgs)
			for d := range msgs {
				s := BytesToString(&(d.Body))
				count++
				fmt.Printf("receve msg is :%s -- %d\n", *s, count)
			}
		}()
	}
}

func BytesToString(b *[]byte) *string {
	s := bytes.NewBuffer(*b)
	r := s.String()
	return &r
}
*/
